package server

import (
	"simple_game/app/libs/logger"
	"sync"
)

const (
	WORLD = iota
	GAME
)

var (
	RoomList = []int32{WORLD, GAME}
	RoomMap  = sync.Map{}
)

type Room struct {
	Type    int32
	Players map[int64]*Player
	Lock    sync.RWMutex
}

func AddRoom(roomType int32, player *Player) {
	load, ok := RoomMap.Load(roomType)
	if !ok {
		logger.ERROR("Room Is Nil", roomType)
		return
	}
	room := load.(*Room)
	room.Lock.Lock()
	defer room.Lock.Unlock()
	room.Players[player.PlayerData.UUid] = player
}

func DelRoom(player *Player) {
	RoomMap.Range(func(key, value interface{}) bool {
		room := value.(*Room)
		delRoomUser(room, player.PlayerData.UUid)
		return true
	})
}

func delRoomUser(room *Room, uuid int64) {
	room.Lock.Lock()
	defer room.Lock.Unlock()
	delete(room.Players, uuid)
}

func init() {
	for _, roomType := range RoomList {
		RoomMap.Store(roomType, &Room{
			Players: map[int64]*Player{},
		})
	}
}
